package cn.easytogo.service.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import cn.easytogo.bean.Usergroup;
import cn.easytogo.bean.UsergroupAndRole;
import cn.easytogo.service.IUsergroupDAO;

public class UsergroupDAOImpl extends BaseService implements IUsergroupDAO {

	public List selectUsergroupsByMap(Map map) throws SQLException {
		return this.getBaseDAO().queryForList("usergroup.selectUsergroups", map);
	}
	public List selectUsergroupsWithoutRolesByMap(Map map) throws SQLException {
		return this.getBaseDAO().queryForList("usergroup.selectUsergroupsWithoutRoles", map);
	}
	public Object insertUsergroup(Usergroup usergroup) throws SQLException {
		try {
			this.getBaseDAO().startTransaction();
			this.getBaseDAO().insert("usergroup.insertUsergroup", usergroup);
			Integer id = (Integer) this.getBaseDAO().queryForObject("usergroup.selectLastInsertId");//获取刚才插入的数据的ID
			usergroup.setId(id.toString());
			insertUsergroupAndRoles(usergroup);
			this.getBaseDAO().commitTransaction();
		} finally {
			this.getBaseDAO().endTransaction();
		}
		return null;
	}

	public Object updateUsergroup(Usergroup usergroup) throws SQLException {
		try {
			this.getBaseDAO().startTransaction();
			this.getBaseDAO().update("usergroup.updateUsergroup", usergroup);
			this.getBaseDAO().delete("usergroup.deleteUsergroupAndRole", usergroup);
			insertUsergroupAndRoles(usergroup);
			this.getBaseDAO().commitTransaction();
		} finally {
			this.getBaseDAO().endTransaction();
		}
		return null;
	}
	/**
	 * 根据usergroup的roleIds属性批量插入UsergroupAndRole
	 * @throws SQLException 
	 * */
	private void insertUsergroupAndRoles(Usergroup usergroup) throws SQLException{
		String roleIds = usergroup.getRoleIds();
		if(roleIds!=null&&!"".equals(roleIds)){
			String[] roleIdArray = roleIds.split(",");
			for (String rId : roleIdArray) {
				UsergroupAndRole uar = new UsergroupAndRole();
				uar.setUser_id(usergroup.getId());
				uar.setRole_id(rId);
				uar.setUsergroup_flag(usergroup.getUsergroup_flag());
				this.getBaseDAO().insert("usergroup.insertUsergroupAndRole",uar);
			}
		}
	}

	public int deleteUsergroup(Usergroup usergroup) throws SQLException {
		try {
			this.getBaseDAO().startTransaction();
			this.getBaseDAO().delete("usergroup.deleteUsergroup", usergroup);
			this.getBaseDAO().delete("usergroup.deleteUsergroupAndRole", usergroup);
			this.getBaseDAO().commitTransaction();
		} finally {
			this.getBaseDAO().endTransaction();
		}
		return 0;
	}
}
